package org.stone.project;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Random;

public class ClientDemo {
    public static void main(String[] args) throws URISyntaxException, InterruptedException, IOException {
        for (int i = 0; i < 1; i++) {
            new Thread(()->{
                try {
                    newClient();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }


        Thread.currentThread().join();
    }

    public static void newClient() throws InterruptedException, URISyntaxException, IOException {
        WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://127.0.0.1:8090/chat")) {
            private BufferedWriter bw ;

            @SneakyThrows
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                System.out.println("连接建立");
                String fileName = "C:/chat/" + UUID.randomUUID().toString() + ".txt";
                File file = new File("C:/chat/" + UUID.randomUUID().toString() + ".txt");
                file.createNewFile();
                bw = new BufferedWriter(new FileWriter(file));
            }

            @SneakyThrows
            @Override
            public void onMessage(String s) {
                System.out.println("收到消息" + s);
                bw.write(s);
                bw.newLine();
            }

            @Override
            public void onClose(int i, String s, boolean b) {
                System.out.println("连接关闭");
            }

            @Override
            public void onError(Exception e) {
                System.out.println("连接错误");
            }
        };
        webSocketClient.connect();
        HashMap<String, Object> param = new HashMap<>();
        param.put("type",1);
        param.put("token","1");
        webSocketClient.send(JSONUtil.toJsonStr(param));
        while(true){
            int sec = Math.abs(new Random().nextInt() % 10);
//            Thread.sleep(sec*1000);
            HashMap<String, Object> msg = new HashMap<>();
            msg.put("messageType",2);
            msg.put("receiveId","1");
            msg.put("receiveType",4);
            msg.put("contentType",1001);
            msg.put("content","测试数据"+System.currentTimeMillis());
            String post = HttpUtil.post("http://127.0.0.1:8083/msg/sendMsgSync", JSONUtil.toJsonStr(msg));
            System.out.println(post);
        }
    }
}
